package com.rr.middle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author RR
 * @date 2024/1/27 14:13
 */
public class MaxNumberOfAlloys {
    public int maxNumberOfAlloys(int n, int k, int budget, List<List<Integer>> composition, List<Integer> stock, List<Integer> cost) {
        int[] result = new int[]{0};
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < k; i++) {
            List<Integer> integers = composition.get(i);
            futures.add(CompletableFuture.supplyAsync(() -> getOne(n, k, budget, integers, stock, cost))
                    .thenAccept(current -> doCompare(result, current)));

        }
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        return result[0];
    }

    private static void doCompare(int[] result, Integer current) {
        if (result[0] < current) {
            result[0] = current;
        }
    }

    private int getOne(int n, int k, int budget, List<Integer> composition, List<Integer> stock, List<Integer> cost) {
        int middle;
        int ans = 0;
        int left = 1;
        int right = Math.min(Integer.MAX_VALUE, budget + Collections.max(stock) * 2);
        while (left <= right) {
            long needBudget = 0;
            middle = (left + right) / 2;
            for (int j = 0; j < n; j++) {
                long kindNeedNum = (long)composition.get(j) * middle - stock.get(j);
                if (kindNeedNum > 0) {
                    needBudget += kindNeedNum * cost.get(j);
                }
            }
            if (needBudget > budget) {
                right = middle - 1;
            } else if (needBudget < budget) {
                ans = middle;
                left = middle + 1;
            } else {
                return middle;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        List<List<Integer>> composition = new ArrayList<>();
        composition.add(Arrays.asList(1));
        List<Integer> stocks = Arrays.asList(77472690);
        List<Integer> cost = Arrays.asList(1);
        MaxNumberOfAlloys obj = new MaxNumberOfAlloys();
        int i = obj.maxNumberOfAlloys(1, 1, 0, composition, stocks, cost);
        System.out.println(i);
    }
}
